import { isNavigationFailure } from 'vue-router'
// import storage from '@/utils/storage.js'
import store from '@/store/index.js'
// import { ACCESS_TOKEN } from '@/store/constantKeys.js'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const DEFAULT_ROUTE_PATH = '/dashboard'
// const LOGIN_ROUTE_PATH = '/login'

// 免登录白名单
const whiteList = ['Login', '404']

// 通过设置false来关闭加载旋转器(默认是显示的)
NProgress.configure({ showSpinner: false })

/**
 * @description 动态添加路由
 */
function setAsyncRoute ({ to, from, next, hasRoute }) {
  // 获取动态路由列表
  store.dispatch('asyncRoute/generateRoutes').then(() => {
    if (whiteList.includes(to.name)) return

    if (!hasRoute) {
      next({ ...to, replace: true })
    }
  }).catch(() => next({ path: DEFAULT_ROUTE_PATH }))
}

/**
 * @description 路由守卫方法
 * @param router
 */
export function createRouterGuards (router) {
  // 全局前置守卫
  router.beforeEach((to, from, next) => {
    NProgress.start()

    // TODO:
    const hasRoute = router.hasRoute(to.name)
    setAsyncRoute({ to, from, next, hasRoute })

    if (whiteList.includes(to.name) || hasRoute) {
      next()
    }

    NProgress.done()

    // 获取token
    // const token = storage.get(ACCESS_TOKEN)
    // if (token) {
    //   if (to.name === 'Login') {
    //     next({ path: DEFAULT_ROUTE_PATH })
    //     NProgress.done()
    //   } else {
    //     const hasRoute = router.hasRoute(to.name)
    //
    //     setAsyncRoute({ to, from, next, hasRoute })
    //
    //     if (whiteList.includes(to.name) || hasRoute) {
    //       next()
    //     }
    //   }
    // } else {
    //   if (whiteList.includes(to.name)) {
    //     next()
    //   } else {
    //     next({
    //       path: LOGIN_ROUTE_PATH,
    //       query: { redirect: to.fullPath },
    //       replace: true
    //     })
    //     NProgress.done()
    //   }
    // }
  })

  // 全局后置守卫
  router.afterEach((to, from, failure) => {
    document.title = to.meta.title || document.title
    if (isNavigationFailure(failure)) {
      console.log('failed navigation', failure)
    }
    // 设置需要缓存的组件名称
    const keepAliveComponents = store.getters['asyncRoute/keepAliveComponents']
    const currentComponent = to.matched.find(item => item.name === to.name)
    if (currentComponent && currentComponent.components.default.name) {
      const currentComponentName = currentComponent.components.default.name
      if (currentComponentName && !keepAliveComponents.includes(currentComponentName) && to.meta.keepAlive) {
        keepAliveComponents.push(currentComponentName)
      } else if (!to.meta.keepAlive || to.name === 'Redirect') {
        // 不需要缓存组件
        const index = store.getters['asyncRoute/keepAliveComponents'].findIndex(name => name === currentComponentName)
        if (index !== -1) {
          keepAliveComponents.splice(index, 1)
        }
      }
    }
    store.commit('asyncRoute/setKeepAliveComponents', keepAliveComponents)
    NProgress.done()
  })

  // 路由出错
  router.onError((error) => {
    console.log(error, '路由错误')
  })
}
